<template>
	<!-- 我的名片 -->
	<view class="my-card">
		<view v-if="loading" class="loading-container">
			<view class="loading">
				<uni-icons type="spinner-cycle" size="30" color="#0360FA"></uni-icons>
				<text>加载中...</text>
			</view>
		</view>
		<view v-else class="my-card-main">
			<view class="head">
				<!--  头部 -->
				<view class="head-top">
					<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/kthy_bg.png"
						mode="aspectFill"></image>
					<view class="head-top-main">
						<view class="head-img">
							<image class="avatar" :src="userInfo.avatar?userInfo.avatar:'/static/images/head_default.png'"
								mode="aspectFill">
							</image>
							<image class="vip" v-if="userInfo.authStatus == '1' || userInfo.authStatus == '2'"
								src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/home_vip.png"
								mode="widthFix">
							</image>
						</view>
						<view class="head-info">
							<view class="head-info-lf">
								<view class="name">
									<button>{{ userInfo.realName }}</button>
								</view>
								<view v-if="userInfo.srStatus !== '1'" class="authentication-status"
									@click="topageGoSm()">{{ myUserId !== userInfo.guid?'未实名':'去实名' }}
									<uni-icons v-if=" myUserId === userInfo.guid" type="right" size="14"
										color="#FFEFD9"></uni-icons>
								</view>
								<view v-if="userInfo.srStatus == '1'"
									class="authentication-status authentication-status-yrz">已实名</view>
							</view>
							<view class="head-info-rt">
								<!-- 点赞 -->
								<view class="like">
									<image v-if="!like.isActive" src="/static/images/like.png" mode="widthFix"
										@click="likeClick()"></image>
									<image v-if="like.isActive" src="/static/images/like_active.png" mode="widthFix"
										@click="cancelLikeClick()"></image>
									<text>{{ like.count }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="head-bottom">
					<view class="head-bottom-lf">
						<view v-if="userInfo.companyName" class="row-text">
							<view class="row-text-lf">
								<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/wdmp_gsmc@2x.png"
									mode="widthFix"></image>公司名称：
							</view>
							<view class="row-text-rt">{{ userInfo.companyName }}</view>
						</view>
						<view class="row-text">
							<view class="row-text-lf">
								<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/wdmp_dz@2x.png"
									mode="widthFix"></image>地址：
							</view>
							<view class="row-text-rt">{{ userInfo.address }}</view>
						</view>
						<view v-if="userInfo.userPosition" class="row-text">
							<view class="row-text-lf">
								<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/wsxx_wdzw@2x.png"
									mode="widthFix"></image>职务：
							</view>
							<view class="row-text-rt">{{ userInfo.userPosition }}</view>
						</view>
						<view class="row-text">
							<view class="row-text-lf">
								<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/wdmp_sj@2x.png"
									mode="widthFix"></image>手机：
							</view>
							<!-- 其他用户进来 -->
							<view v-if="myUserId !== userInfo.guid" class="row-text-rt" :class="{'no-click': userInfo.isHidden}" @click="userInfo.isHidden ? null : handlePhoneClick()">
								{{ userInfo.isHidden ? maskPhone(userInfo.telephone) : (myUserType === '普通用户' ? (showContactInfo ? userInfo.telephone : maskPhone(userInfo.telephone)) : userInfo.telephone) }}
							</view>
							<!-- 我自己进来 -->
							<view v-if="myUserId === userInfo.guid" class="row-text-rt">
								{{ showContactInfo1 ? maskPhone(userInfo.telephone) : userInfo.telephone }}
							</view>
						</view>
						<view class="row-text">
							<view class="row-text-lf">
								<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/wdmp_wx@2x.png"
									mode="widthFix"></image>微信：
							</view>
							<!-- 其他用户进来 -->
							<view v-if="myUserId !== userInfo.guid" class="row-text-rt" :class="{'no-click': userInfo.isHidden}" @click="userInfo.isHidden ? null : handleWeixinClick()">
								{{ userInfo.isHidden ? maskWeixin(userInfo.wxOpenId) : (myUserType === '普通用户' ? (showContactInfo ? userInfo.wxOpenId : maskWeixin(userInfo.wxOpenId)) : userInfo.wxOpenId) }}
							</view>
							<!-- 我自己进来 -->
							<view v-if="myUserId === userInfo.guid" class="row-text-rt">
								{{showContactInfo1 ? maskWeixin(userInfo.wxOpenId) : userInfo.wxOpenId }}
							</view>
						</view>
					</view>
					<view class="head-bottom-rt">
						<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/cysj_bg.png"
							mode="widthFix"></image>
						<view class="text-w">
							<view class="text1">从业时间</view>
							<view class="text2"><text>{{ userInfo.workYear }}</text></view>
						</view>
					</view>
				</view>
				<view v-if="myUserType === '普通用户' && myUserId !== userInfo.guid && !userInfo.isHidden"
					class="show-contact-btn" @click="handleShowContact">
					<view class="btn-content">
						<uni-icons :type="showContactInfo ? 'eye-slash' : 'eye'" size="16" color="#AC6C17"></uni-icons>
						<text>{{showContactInfo ? '隐藏联系人信息' : '显示联系人完整信息'}}</text>
					</view>
				</view>
				<!-- 如果我是vip我可以设置我的联系方式隐藏 -->
				<view v-if="(userInfo.authStatus == '1' || userInfo.authStatus == '2') && myUserId == userInfo.guid" class="show-contact-btn"
					@click="myhandleShowContact(!showContactInfo1)">
					<view class="btn-content">
						<uni-icons :type="showContactInfo1 ? 'eye' : 'eye-slash'" size="16" color="#AC6C17"></uni-icons>
						<text>{{showContactInfo1 ? '显示我的信息' : '隐藏我的信息'}}</text>
					</view>
				</view>
			</view>
			<view class="hxyw">
				<view class="title">核心业务</view>
				<view class="ywfw-wrapper">
					<view class="block" v-for="(item, index) in userInfo.userScope" :key="index">{{item}}</view>
				</view>
			</view>
		</view>
		<view v-if="!ui.isMyCard" class="public-btn-w public-btn-w1">
			<button class="public-btn public-btn-blue"
				:class="follow.isActive?'public-btn-red':ui.isBtnActive?'active':''" @touchstart="ui.isBtnActive = true"
				@touchend="ui.isBtnActive = false" @click="toggleFollow()">{{ follow.isActive?'取消关注':'加关注' }}</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				ui: {
					isBtnActive: false,
					isMyCard: true
				},
				like: {
					count: 0,
					isActive: false,
					data: []
				},
				follow: {
					isActive: false,
					data: []
				},
				userId: '',
				myUserType: '',
				myUserId: '',
				userInfo: {
					authStatus: '',
					avatar: '',
					realName: '',
					workYear: '',
					userScope: [],
					guid: ''
				},
				showContactInfo: false,
				showContactInfo1: false,
				loading: true,
				pageParam: null
			}
		},
		async onLoad(param) {
			// 保存页面参数
			if (param && param.id) {
				this.pageParam = param;
				await this.initPageData(param);
			} else {
				// 无参数时获取当前用户信息
				this.myUserType = this.$store.state.user.userInfo.userType;
				this.myUserId = this.$store.state.user.userInfo.guid;
				this.userInfo = {
					...this.$store.state.user.userInfo
				};
				this.showContactInfo1 = this.$store.state.user.userInfo.isHidden;
				this.userId = this.userInfo.guid;
				await this.init(this.userId); // 获取点赞信息
				this.loading = false; // 数据加载完成后关闭loading
			}
		},
		async onShow() {
			// 在页面显示时，如果有存储的参数则重新加载数据
			if (this.pageParam) {
				await this.initPageData(this.pageParam);
			} else if (this.userId) {
				// 无参数时刷新当前用户信息
				this.userInfo = {
					...this.$store.state.user.userInfo
				};
				await this.init(this.userId);
			}
		},
		methods: {
			async initPageData(param) {
				this.loading = true; // 开始加载数据时显示loading
				this.myUserType = this.$store.state.user.userInfo.userType
				this.myUserId = this.$store.state.user.userInfo.guid

				this.userInfo = {
					authStatus: '',
					avatar: '',
					realName: '',
					workYear: '',
					userScope: [],
					guid: ''
				}
				this.like = {
					count: 0,
					isActive: false,
					data: []
				}
				this.follow = {
					isActive: false,
					data: []
				}

				this.userId = param.id
				this.ui.isMyCard = false;

				try {
					const [likeRes, followRes, lookRes, detailRes] = await Promise.all([
						this.init(param.id),
						this.initGz(this.$store.state.user.userInfo.guid),
						this.initLook(param.id),
						this.getDetail(param.id)
					])

					if (detailRes && detailRes.succ) {
						this.userInfo = {
							...detailRes.data
						}
					}
				} catch (error) {
					console.error('加载数据失败:', error)
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
				} finally {
					this.loading = false; // 数据加载完成后关闭loading
				}
			},
			async init(id) {
				const requestData = {
					userId: id
				};
				const res = await this.$api.infoCardInfoDz(requestData);
				if (res.succ) {
					this.like.count = res.data.length;
					if (res.data.length > 0) {
						this.like.data = res.data
						const isLike = res.data.some(item => item.dzUserId === this.$store.state.user.userInfo.guid);
						if (isLike) {
							this.like.isActive = true;
						} else {
							this.like.isActive = false;
						}
					} else {
						this.like.data = []
						this.like.isActive = false
					}
				}
			},
			async initGz(id) {
				const requestData = {
					userId: id
				};
				const res = await this.$api.infoCardInfoAttention(requestData);
				if (res.succ) {
					this.follow.data = res.data
					if (res.data.length > 0) {
						const isAttention = res.data.some(item => item.guid === this.userId);
						if (isAttention) {
							this.follow.isActive = true;
						} else {
							this.follow.isActive = false;
						}
					} else {
						this.follow.data = []
						this.follow.isActive = false
					}
				}
			},
			async initLook(id) {
				const requestData = {
					userId: id,
					lookUserId: this.$store.state.user.userInfo.guid
				};
				const res = await this.$api.infoCreateLook(requestData);
			},
			async getDetail(id) {
				const requestData = {
					guid: id
				};
				const res = await this.$api.getInfo(requestData);
				return res;
			},
			async toggleFollow() {
				const data = {
					attentionUserId: this.userId,
					userId: this.$store.state.user.userInfo.guid
				};

				try {
					const api = this.follow.isActive ?
						this.$api.infoCardDeleteAttention :
						this.$api.infoCardCreateAttention;

					const res = await api(data);

					if (res.succ) {
						await this.initGz(this.$store.state.user.userInfo.guid);
						if (this.follow.isActive) {
							await this.initMessage(this.follow.isActive)
						}
						uni.showToast({
							title: `${!this.follow.isActive ? '取消' : ''}关注成功`,
							icon: 'success'
						});
					}
				} catch (err) {
					console.error('关注操作失败:', err);
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					});
				}
			},
			async likeClick() {
				const data = {
					dzUserId: this.$store.state.user.userInfo.guid,
					userId: this.userId
				};
				const res = await this.$api.infoCardCreateDz(data);
				console.log(res);
				if (res.succ) {
					this.init(this.userId)
					uni.showToast({
						title: '点赞成功',
						icon: 'success'
					});
				}
			},
			cancelLikeClick() {
				this.like.data.forEach(async item => {
					if (item.dzUserId === this.$store.state.user.userInfo.guid) {
						const data = {
							...item
						};
						const res = await this.$api.infoCardDeleteDz(data);
						console.log(res);
						if (res.succ) {
							this.init(this.userId)
							uni.showToast({
								title: '取消点赞成功',
								icon: 'success'
							});
						}
					}
				})
			},
			async initMessage(isActive) {
				let text = '';
				if (isActive) {
					text = '关注'
				} else {
					text = '取消关注'
				}
				let msgCn = '用户' + this.$store.state.user.userInfo.realName + text + '了你';
				const data = {
					createUserId: this.$store.state.user.userInfo.guid,
					msgUserId: this.userId,
					msgType: "0",
					msgCn: msgCn,
					msgJumpId: this.$store.state.user.userInfo.guid,
					createUserName: this.$store.state.user.userInfo.realName
				}
				const res = await this.$api.getMsgCreate(data);
				console.log('res', res);
			},
			// 如果我是vip我可以设置我的联系方式隐藏 
			async myhandleShowContact(stutas) {
				const requestData = {
					...this.userInfo,
					isHidden: stutas
				};
				const res = await this.$api.infoLogin(requestData);
				console.log(res)
				this.$store.dispatch('user/setUserInfo', res.data);
				this.showContactInfo1 = this.$store.state.user.userInfo.isHidden;
			},
			async handleShowContact() {
				if (this.showContactInfo) {
					this.showContactInfo = false;
				} else {
					try {
						let data = {
							userId: this.$store.state.user.userInfo.guid,
							phone: this.userInfo.telephone,
						}
						const res = await this.$api.getCheckPhone(data);
						if (res.succ) {
							this.showContactInfo = true;
						} else {
							uni.showToast({
								title: res.message || '今日次数已用完',
								icon: 'none'
							});
						}
					} catch (e) {
						uni.showToast({
							title: '网络异常，请稍后重试',
							icon: 'none'
						});
					}
				}
			},
			// 去实名
			topageGoSm() {
				if (this.myUserId === userInfo.guid) {
					uni.navigateTo({
						url: '/pages/rlrz/rlrz'
					});
				}

			},
			maskPhone(phone) {
				if (!phone) return '-';
				return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
			},
			maskWeixin(weixin) {
				if (!weixin) return '-';
				const length = weixin.length;
				if (length <= 2) return weixin;
				return weixin.charAt(0) + '*'.repeat(length - 2) + weixin.charAt(length - 1);
			},
			previewAvatar() {
				if (this.userInfo.avatar) {
					uni.previewImage({
						urls: [this.userInfo.avatar],
						current: this.userInfo.avatar
					});
				}
			},
			handlePhoneClick() {
				// 处理电话点击事件
				// 如果用户设置了隐藏联系方式，则不允许任何用户点击
				if (this.userInfo.isHidden) {
					uni.showToast({
						title: '该用户已隐藏联系方式',
						icon: 'none'
					});
					return;
				}
				
				if (this.showContactInfo || this.myUserType !== '普通用户' || this.myUserId === this.userInfo.guid) {
					if (this.userInfo.telephone) {
						uni.makePhoneCall({
							phoneNumber: this.userInfo.telephone,
							fail: (err) => {
								console.error('拨打电话失败:', err);
								uni.showToast({
									title: '拨打电话失败',
									icon: 'none'
								});
							}
						});
					}
				}
			},
			handleWeixinClick() {
				// 处理微信点击事件
				// 如果用户设置了隐藏联系方式，则不允许任何用户点击
				if (this.userInfo.isHidden) {
					uni.showToast({
						title: '该用户已隐藏联系方式',
						icon: 'none'
					});
					return;
				}
				
				if (this.showContactInfo || this.myUserType !== '普通用户' || this.myUserId === this.userInfo.guid) {
					if (this.userInfo.wxOpenId) {
						uni.setClipboardData({
							data: this.userInfo.wxOpenId,
							success: () => {
								uni.showToast({
									title: '微信号已复制',
									icon: 'success'
								});
							},
							fail: (err) => {
								console.error('复制微信号失败:', err);
								uni.showToast({
									title: '复制失败',
									icon: 'none'
								});
							}
						});
					}
				}
			}
		}
	}
</script>

<style lang="less">
	.my-card {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: linear-gradient(180deg, #FAEBDB 0%, rgba(255, 247, 238, 0) 500rpx);

		.loading-container {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			background: #fff;

			.loading {
				display: flex;
				flex-direction: column;
				align-items: center;

				text {
					margin-top: 20rpx;
					color: #666;
					font-size: 28rpx;
				}
			}
		}

		.my-card-main {
			flex: 1;
		}

		.head {
			margin: 30rpx;
			background: #FFF7EE;
			padding-bottom: 30rpx;
			border-radius: 20rpx;

			.head-top {
				position: relative;

				>image {
					z-index: 1;
					position: relative;
					width: 100%;
					height: 202rpx;
					border-radius: 20rpx;
				}

				.head-top-main {
					z-index: 2;
					position: absolute;
					left: 0;
					top: 0;
					width: 100%;
					height: 100%;
					display: flex;
					align-items: center;
				}

				.head-img {
					position: relative;
					width: 120rpx;
					height: 120rpx;
					border: 6rpx solid #FFD46D;
					margin-left: 24rpx;
					border-radius: 100%;

					.avatar {
						width: 120rpx;
						height: 120rpx;
						object-fit: cover;
						border-radius: 100%;
					}

					.vip {
						width: 38rpx;
						height: 31rpx;
						position: absolute;
						right: -10rpx;
						top: 4rpx;
					}
				}

				.head-info {
					flex: 1;
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-left: 28rpx;

					.head-info-lf {
						display: flex;
						flex-direction: column;

						.name {
							margin-top: 20rpx;

							button {
								background: none;
								border: none;
								outline: none;
								padding: 0;
								line-height: 1;
								font-size: 40rpx;
								color: #F8EFD8;
								font-weight: bold;

								&::after {
									border: none;
								}
							}
						}


						.authentication-status {
							height: 64rpx;
							display: flex;
							align-items: center;
							font-size: 30rpx;
							color: #FFEFD9;
							margin-top: 20rpx;

							.uni-icons {
								margin-left: 10rpx;
							}
						}
					}

					.head-info-rt {
						margin-right: 50rpx;

						// 点赞
						.like {
							display: flex;
							align-items: center;

							image {
								width: 39.64rpx;
								height: 37.92rpx;
								margin-right: 10rpx;
							}

							text {
								color: #FFEFD9;
								font-size: 36rpx;
								margin-top: 6rpx;
								font-weight: bold;
							}
						}
					}
				}
			}

			.head-bottom {
				position: relative;
				display: flex;
				align-items: center;
				padding: 30rpx 10rpx 20rpx 30rpx;
				overflow: hidden;

				.head-bottom-lf {
					flex: 1;
					display: flex;
					flex-direction: column;
					overflow: hidden;
				}

				.row-text {
					display: flex;
					align-items: center;
					padding: 18rpx 0;

					.row-text-lf {
						display: flex;
						align-items: center;
						font-size: 28rpx;
						color: #333;
						flex-shrink: 0;

						image {
							width: 44rpx;
							height: 44rpx;
							margin-right: 10rpx;
						}
					}

					.row-text-rt {
						font-size: 28rpx;
						color: #333;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						
						&.no-click {
							color: #999;
							cursor: not-allowed;
						}
					}
				}

				.head-bottom-rt {
					position: absolute;
					right: 0;
					width: 245rpx;
					height: 216rpx;
					flex-shrink: 0;

					image {
						z-index: 1;
						position: relative;
						width: 100%;
						height: 100%;
					}

					.text-w {
						z-index: 2;
						position: absolute;
						left: 0;
						top: 0;
						width: 100%;
						height: 100%;
						display: flex;
						flex-direction: column;
						align-items: center;

						.text1 {
							color: #AC6C17;
							font-size: 30rpx;
							margin-top: 50rpx;
						}

						.text2 {
							margin-top: 10rpx;

							text {
								color: #AC6C17;
								font-size: 30rpx;
								font-weight: bold;
							}
						}
					}
				}

			}
		}

		.hxyw {
			margin: 0 30rpx;
			padding: 30rpx;
			background-color: #FFF7EE;
			border-radius: 20rpx;

			.title {
				color: #333;
				font-size: 36rpx;
				font-weight: bold;
				margin-bottom: 30rpx;
				position: relative;
				padding-left: 25rpx;

				&::before {
					content: '';
					position: absolute;
					left: 0;
					top: 50%;
					transform: translateY(-50%);
					width: 6rpx;
					height: 30rpx;
					background: #E6B26D;
					border-radius: 3rpx;
				}
			}

			.ywfw-wrapper {
				display: flex;
				flex-wrap: wrap;
				gap: 20rpx;

				.block {
					max-width: 160rpx;
					padding: 12rpx 20rpx;
					background: #FFEFD9;
					border-radius: 12rpx;
					color: #AC6C17;
					font-size: 28rpx;
					text-align: center;
					transition: all 0.3s ease;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}
			}
		}

		.public-btn-w {
			margin: 20rpx 30rpx;

			&.public-btn-w1 {
				.public-btn-blue {
					background: linear-gradient(138deg, #F3B359 0%, #EC6A34 100%);
					border-radius: 44rpx;
				}

				.public-btn-red {
					background: linear-gradient(90deg, #F77815 0%, #e26c12 100%);
					border-radius: 44rpx;
				}
			}
		}

		.show-contact-btn {
			display: flex;
			padding: 0 30rpx;

			.btn-content {
				display: flex;
				align-items: center;
				padding: 12rpx 24rpx;
				background-color: #FFEFD9;
				border-radius: 30rpx;
				transition: all 0.3s;

				&:active {
					opacity: 0.8;
				}

				text {
					color: #AC6C17;
					font-size: 28rpx;
					margin-left: 8rpx;
				}
			}
		}
	}
</style>